require "warchiver/version"

##
# Warchiver Module
module Warchiver
	##
	# Dependencies
	require 'uri'
	require 'open-uri'
	require 'fileutils'

	##
	# Configuration
	class << self
		attr_accessor :configuration
	end

	def self.configure
		self.configuration ||= Configuration.new
		yield(configuration)
	end

	class Configuration
		attr_accessor :user_agent, :base_directory

		def initialize
			@base_directory = "/"
			@user_agent = "Ruby/#{RUBY_VERSION}/Warchiver"
		end
	end


	class Archiver
		def checkMake(directory)
			if File.directory?(directory)
				FileUtils.cd(directory)
			else
				FileUtils.mkdir(directory)
				FileUtils.cd(directory)
			end
		end
		def initialize(url)
			@url = url
			config = Configuration.new
			@string = ""
			open(@url, "User-Agent" => config.instance_variable_get(:@user_agent)) do |f|
				f.each_line { |line| @string << line }
			end
			FileUtils.cd(config.instance_variable_get(:@base_directory))
			checkMake("archived")
			checkMake(Time.now.to_i.to_s)
			checkMake((@url.gsub(/(\:)+/i, "...colon...")).gsub(/(\/)+/i, "...slash..."))
			FileUtils.touch("index")
			File.open("index", 'w') { |file| file.write(@string) }
		end
	end
end